﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Seven.Site.Mvc.Filters
{
    /// <summary>
    /// 获取菜单按钮权限的过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class GetButtonPermissionsAttribute : ActionFilterAttribute
    {
        #region 属性

        /// <summary>
        /// 当前控制器名称
        /// </summary>
        private string ControllerName { get; set; }

        /// <summary>
        /// 当前动作名称
        /// </summary>
        private string ActionName { get; set; }

        /// <summary>
        /// 指定动作名称
        /// </summary>
        private string SpecialActionName { get; set; }

        /// <summary>
        /// 分组标记
        /// </summary>
        private IEnumerable<string> GroupMarks { get; set; }

        #endregion

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="groupMarks">分组标记，表示只获取当前ControllerName和当前ActionName下指定分组标记的按钮权限数据。若多个，可以用英文逗号相连。不区分大小写。并且将以ViewData["ButtonPermissionsGroup" + 索引号（1开始）]的形式传入视图中。</param>
        /// <param name="specialActionName">特定的action名称，表示只获取当前ControllerName和特定ActionName下指定分组标记的按钮权限数据。</param>
        public GetButtonPermissionsAttribute(string groupMarks = "", string specialActionName = "")
        {
            this.SpecialActionName = specialActionName;
            this.GroupMarks = groupMarks.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        }

        /// <summary>
        /// 在Action结果返回之前执行
        /// </summary>
        /// <param name="filterContext">筛选器上下文</param>
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            this.ControllerName = filterContext.RouteData.Values["controller"].ToString();
            this.ActionName = !string.IsNullOrWhiteSpace(this.SpecialActionName) ? this.SpecialActionName : filterContext.RouteData.Values["action"].ToString();

            filterContext.Controller.ViewData["ButtonPermissions"] = new Seven.Service.Security.Account().GetCurrentUserButtons(this.ControllerName, this.ActionName, this.GroupMarks);
            int k = 1;
            foreach (var item in this.GroupMarks)
            {
                filterContext.Controller.ViewData["ButtonPermissionsGroup" + k] = item;
                k++;
            }

            base.OnResultExecuting(filterContext);
        }
    }
}
